package com.wxq.product.service.impl;

import com.wxq.common.constant.ProductConstant;
import com.wxq.common.to.SkuEsModel;
import com.wxq.common.to.SkuHasStockTO;
import com.wxq.common.to.SpuBoundTO;
import com.wxq.common.utils.R;
import com.wxq.product.entity.*;
import com.wxq.product.feign.CouponFeignService;
import com.wxq.product.feign.SearchFeignService;
import com.wxq.product.feign.WareFeignService;
import com.wxq.product.service.*;
import com.wxq.product.vo.Bounds;
import com.wxq.product.vo.Skus;
import com.wxq.product.vo.SpuV0;
import com.wxq.product.dao.SpuInfoDao;
import com.wxq.product.entity.*;
import com.wxq.product.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxq.common.utils.PageUtils;
import com.wxq.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 发布商品
     * @param spuV0
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuV0 spuV0) {
        //1.保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuV0,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());;
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2保存spu的描述图片
        List<String> decript = spuV0.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity(){{
            setSpuId(spuInfoEntity.getId());
            setDecript(String.join(",",decript));
        }};
        spuInfoDescService.save(spuInfoDescEntity);
        //3baocunspu图片集
        List<String> images = spuV0.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //4.保存spu的积分信息，垮裤操作，feign远程调用
        //yomall-sms-sms_spu_bounds
        Bounds bounds = spuV0.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds,spuBoundTO);
        spuBoundTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if (r.getCode() != 0){
            log.error("调用远程服务 yomall-coupon 保存积分信息失败");
        }

        // 6.保存spu对应的sku信息
        // sku基本信息 pms_sku_info
        // sku的图片集 pms_sku_images
        // sku的销售属性信息 pms_sku_sale_attr_value
        // sku的满件优惠，满价优惠，会员价等信息，跨库操作
        // yomall-sms -> sms_sku_ladder, sms_sku_full_reduction, sms_member_price
        List<Skus> skuses = spuV0.getSkus();
        if (skuses != null && skuses.size() > 0){
            skuInfoService.saveSkuInfo(spuInfoEntity,skuses);
        }



    }

    /**
     * spu检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            }); }
        String status = (String)params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String brandId = (String)params.get("brandId");
        if (!StringUtils.isEmpty(brandId)  && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String)params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)  && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);

    }

    /**
     * 商品上架
     * @param spuId
     * @return
     */
    @Override
    public void up(Long spuId) {
        //组装数据
        //查询当前sku的所有可以被用来检索规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.listBaseAttrForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //在指定属性集合里面，查找出能够被检索的属性
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(attr ->{
            return idSet.contains(attr.getAttrId());
        }).map(attr ->{
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(attr,attrs);
            return attrs;
        }).collect(Collectors.toList());
        //查询当前spuId对应所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        //发送远程调用，库存系统查询是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long,Boolean> stockMap = null;
        try {
            List<SkuHasStockTO> tos = wareFeignService.getSkuHasStock(skuIds);
            stockMap = tos.stream().collect(Collectors.toMap(SkuHasStockTO::getSkuId,value->
                value.getHasStock()
            ));
        }catch (Exception e){
            log.error("调用远程库存服务 yomall-ware 查询异常:{}", e);
        }
        //封装每个sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModelList = skus.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity,skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //远程调用异常，默认设置有库存
            if (finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }
            //热度
            skuEsModel.setHotScore(0L);
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //将数据发给es保存
        R r = searchFeignService.productUp(skuEsModelList);
        if (r.getCode() == 0){
            //远程调用成功
            //更新spu状态为已上架
            baseMapper.updataSpuSttus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }

}